package myprotocol;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MyProtocalServer {
	private static final int PORT = 2500;
	static Logger logger = Logger.getLogger(MyProtocalServer.class);

	public static void main(String[] args) throws IOException {
		
		IoAcceptor acceptor = new NioSocketAcceptor();

		acceptor.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new MyProtocalCodecFactory(Charset
						.forName("UTF-8"))));
		acceptor.getSessionConfig().setReadBufferSize(1024);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		acceptor.setHandler(new MyHandler());
		acceptor.bind(new InetSocketAddress(PORT));
		System.out.println("start server ...");
	}
}

class MyHandler extends IoHandlerAdapter {
	static Logger logger = Logger.getLogger(MyHandler.class);

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		MyProtocalPack pack = (MyProtocalPack) message;
		logger.debug("收到：" + pack);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		logger.debug("IDLE " + session.getIdleCount(status));
	}
}
